<template>
    <!-- <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
        open
    </el-button> -->
    <el-avatar shape="square" :size="100" :fit="fit" :src="props.modelValue" @click="drawer = true">
        <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="">
    </el-avatar>
    <el-drawer v-model="drawer" title="本地图库" direction="ttb" size="45%">
        <el-upload v-model:file-list="fileList" list-type="picture-card" :auto-upload="false" :on-change="onChange">
            <el-icon>
                <Plus />
            </el-icon>

            <template #file="{ file }">
                <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="getImgUrl(file.url)">
                            <el-icon><zoom-in /></el-icon>
                        </span>

                    </span>
                </div>
            </template>
        </el-upload>
    </el-drawer>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { UploadApi } from '../api';
const drawer = ref(false);
const imgurl =ref("")
const fileList = ref([
    {
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
    }
])
//编辑触发函数
const onChange = (uploadFile, uploadFiles) => { 
    // console.log('uploadFile=', uploadFile)
    // console.log('uploadFiles=', uploadFiles);
    let name = uploadFile.name
    console.log(name);
    let file = uploadFile.raw
    // console.log(file);
    let reader = new FileReader()
    //读取 file 内容，读取完成后执行 onload 方法
    reader.readAsDataURL(file)
    reader.onload = () => { 
        // 读取完成后，将图片的 base64 数据提取出来
        console.log(reader.result);
        callUploadApi(name, reader.result)

    }

}
const getImgUrl = (imageUrl) => { 
    console.log(imageUrl);
    // 点击给头像赋值 图片地址
    // imgurl.value = imageUrl
    emit('update:modelValue', imageUrl)
    //关闭抽屉组件
    drawer.value = false
}
// 定义一个接收父组件传递过来的图片地址的属性
const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})
// 子向父组件传递图片地址
const emit = defineEmits(['update:modelValue'])

onMounted(() => { 
    callUploadList()
})
const callUploadApi = (name,base64) => { 
    UploadApi.upload.call({name:name,base64:base64}).then(res => { 
        console.log(res);

        callUploadList()
    })
}
//图片列表
const callUploadList = () => { 
    UploadApi.imglist.call().then(res => { 
        // console.log(res);
        fileList.value = res
    })
}
</script>

<style scoped>

</style>